<template>
  <div class="product-detail">
    <div v-if="loading" class="loading">
      加载中...
    </div>

    <template v-else-if="product">
      <div class="product-content">
        <!-- 商品图片展示 -->
        <div class="product-gallery">
          <div class="main-image">
            <img :src="selectedImage" :alt="product.name">
          </div>
          <div class="thumbnail-list">
            <img 
              v-for="(image, index) in product.images" 
              :key="index"
              :src="image"
              :alt="product.name"
              :class="{ active: selectedImage === image }"
              @click="selectedImage = image"
            >
          </div>
        </div>

        <!-- 商品信息 -->
        <div class="product-info">
          <h1>{{ product.name }}</h1>
          
          <div class="price-section">
            <template v-if="product.discount > 0">
              <div class="discounted-price">
                ¥{{ (product.price * (1 - product.discount / 100)).toFixed(2) }}
              </div>
              <div class="original-price">
                原价: ¥{{ product.price }}
              </div>
              <div class="discount-tag">
                {{ product.discount }}% OFF
              </div>
            </template>
            <div v-else class="price">
              ¥{{ product.price }}
            </div>
          </div>

          <div class="stock-info">
            库存: {{ product.stock }} 件
          </div>

          <div class="description">
            {{ product.description }}
          </div>

          <div class="specifications" v-if="product.specifications">
            <h3>商品规格</h3>
            <div v-for="(value, key) in product.specifications" :key="key" class="spec-item">
              <span class="spec-label">{{ key }}:</span>
              <span class="spec-value">{{ value }}</span>
            </div>
          </div>

          <!-- 购买区域 -->
          <div class="purchase-section">
            <div class="quantity-selector">
              <button 
                @click="quantity > 1 && quantity--"
                :disabled="quantity <= 1"
              >-</button>
              <input 
                type="number" 
                v-model.number="quantity"
                min="1"
                :max="product.stock"
              >
              <button 
                @click="quantity < product.stock && quantity++"
                :disabled="quantity >= product.stock"
              >+</button>
            </div>

            <div class="action-buttons">
              <button 
                class="add-to-cart"
                @click="handleAddToCart"
                :disabled="!product.stock"
              >
                加入购物车
              </button>
              <button 
                class="buy-now"
                @click="handleBuyNow"
                :disabled="!product.stock"
              >
                立即购买
              </button>
            </div>
          </div>
        </div>
      </div>
    </template>

    <div v-else class="error">
      商品不存在或已下架
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { useCartStore } from '@/stores/cart'
import type { Product } from '@/types'
import api from '@/api/auth'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()
const cartStore = useCartStore()

const product = ref<Product | null>(null)
const selectedImage = ref('')
const quantity = ref(1)
const loading = ref(true)

// 获取商品详情
const fetchProduct = async () => {
  try {
    loading.value = true
    const response = await api.get(`/products/${route.params.id}`)
    product.value = response
    selectedImage.value = response.images[0]
  } catch (error) {
    console.error('Failed to fetch product:', error)
  } finally {
    loading.value = false
  }
}

// 添加到购物车
const handleAddToCart = async () => {
  if (!userStore.isAuthenticated) {
    router.push('/login')
    return
  }

  if (!product.value) return

  try {
    const success = await cartStore.addToCart(product.value._id, quantity.value)
    if (success) {
      alert('已添加到购物车')
    }
  } catch (error) {
    console.error('Failed to add to cart:', error)
    alert('添加失败，请重试')
  }
}

// 立即购买
const handleBuyNow = async () => {
  if (!userStore.isAuthenticated) {
    router.push('/login')
    return
  }

  if (!product.value) return

  try {
    const success = await cartStore.addToCart(product.value._id, quantity.value)
    if (success) {
      router.push('/mall/cart')
    }
  } catch (error) {
    console.error('Failed to add to cart:', error)
    alert('操作失败，请重试')
  }
}

onMounted(() => {
  fetchProduct()
})
</script>

<style scoped>
.product-detail {
  padding: 2rem;
  max-width: 1200px;
  margin: 0 auto;
}

.loading,
.error {
  text-align: center;
  padding: 4rem 0;
  color: #666;
}

.product-content {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 2rem;
}

.product-gallery {
  position: sticky;
  top: 2rem;
}

.main-image {
  width: 100%;
  aspect-ratio: 1;
  border-radius: 8px;
  overflow: hidden;
  margin-bottom: 1rem;
}

.main-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.thumbnail-list {
  display: flex;
  gap: 0.5rem;
  overflow-x: auto;
}

.thumbnail-list img {
  width: 80px;
  height: 80px;
  object-fit: cover;
  border-radius: 4px;
  cursor: pointer;
  opacity: 0.6;
  transition: opacity 0.2s;
}

.thumbnail-list img.active,
.thumbnail-list img:hover {
  opacity: 1;
}

.product-info {
  padding: 1rem;
}

.product-info h1 {
  margin: 0 0 1rem;
  font-size: 1.8rem;
  color: #333;
}

.price-section {
  margin-bottom: 1rem;
}

.price,
.discounted-price {
  font-size: 1.5rem;
  color: #ff4444;
  font-weight: bold;
}

.original-price {
  color: #999;
  text-decoration: line-through;
  margin-left: 0.5rem;
}

.discount-tag {
  display: inline-block;
  background-color: #ff4444;
  color: white;
  padding: 0.25rem 0.5rem;
  border-radius: 4px;
  margin-left: 0.5rem;
}

.stock-info {
  color: #666;
  margin-bottom: 1rem;
}

.description {
  color: #666;
  line-height: 1.6;
  margin-bottom: 2rem;
}

.specifications {
  margin-bottom: 2rem;
}

.specifications h3 {
  margin-bottom: 1rem;
  color: #333;
}

.spec-item {
  display: flex;
  margin-bottom: 0.5rem;
}

.spec-label {
  color: #666;
  width: 100px;
}

.quantity-selector {
  display: flex;
  align-items: center;
  margin-bottom: 1rem;
}

.quantity-selector button {
  width: 36px;
  height: 36px;
  border: 1px solid #ddd;
  background: white;
  cursor: pointer;
}

.quantity-selector button:disabled {
  background-color: #f5f5f5;
  cursor: not-allowed;
}

.quantity-selector input {
  width: 60px;
  height: 36px;
  text-align: center;
  border: 1px solid #ddd;
  border-left: none;
  border-right: none;
}

.action-buttons {
  display: flex;
  gap: 1rem;
}

.action-buttons button {
  flex: 1;
  padding: 1rem;
  border: none;
  border-radius: 4px;
  font-size: 1rem;
  cursor: pointer;
  transition: opacity 0.2s;
}

.action-buttons button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.add-to-cart {
  background-color: #ff9500;
  color: white;
}

.buy-now {
  background-color: #ff4444;
  color: white;
}
</style> 